/*jslint vars: true, forin: true, sloppy: true */
/*global probe, angular */
probe.controller('Login', function ($scope, $element, ocDialog, ocAPI) {
	var $captcha = '',
		loginDI = ocDialog.queryDI($element);

	$scope.user = {
		username: '',
		password: ''
	};

	$scope.isCaptchaException = false;
	$scope.isAuthException = false;
	$scope.login = function () {
		$scope.isAuthException = false;
		$scope.isCaptchaException = false;

		ocAPI.use('login').by($scope.user, $scope.captcha()).then(function (data) {
			ocDialog.getNewDI('user/account').then(function (DI) {
				DI.openDialogFrom(loginDI);
				ocAPI.getNow();
			});
		}, function (msg) {
			if (msg === 3) {
				$scope.isCaptchaException = true;
			} else if (msg.state === 419) {
				ocDialog.getNewDI('user/active', angular.extend($scope.user, msg.data))
					.then(function (DI) {
						DI.openDialogFrom(loginDI);
					});
			} else {
				$scope.isAuthException = true;
			}
			ocAPI.getNow();
		});
	};

	$scope.register = {
		name: 'user/register',
		closeButtonFn: ocAPI.getNow
	};

	$scope.captcha = function (newValue) {
		if (angular.isDefined(newValue)) {
			$scope.isCaptchaException = false;
			$captcha = newValue.substr(0, 4);
		}
		return $captcha;
	};

	$scope.resetError = function () {
		$scope.isAuthException = false;
	};
});
